<script lang="ts" setup>
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { cloneDeep, debounce, throttle } from 'lodash-es'
import { couponEnable } from '@fl/api/anjutong'
import { addBuildingContact, getProjectList, useDeleteBuildingContact, useQueryContactPersonList } from '@fl/api/anjutong/seckill-manage'
import { SearchForm, SearchTable } from '@fl/components'

import { useRouter } from 'vue-router'

import { useUserStore } from '@fl/store/modules/user'
import { formatTime } from '@fl/utils'

const router = useRouter()
const userStore = useUserStore()
const stateOptions = ref([
    {
        label: '全部',
        value: 'all',
    },
    {
        label: '启用',
        value: '1',
    },
    {
        label: '禁用',
        value: '0',
    },
])

const addVisible = ref(false)
const form = reactive({
    id: '',
    state: '',
    projectBaseId: '',
    buildingName: '',
    contactName: '',
    contactPhone: '',
    consultantList: [
        {
            consultantName: '',
            consultantPhone: '',
        },
    ],
})

const initialState = {
    buildingName: '', // 项目名称
    contactName: '', // 券名称
    contactPhone: '',
    consultant: '',
}

const formRules = reactive({
    projectBaseId: [
        { required: true, message: '请选择楼盘', trigger: 'change' },
    ],
    contactName: [
        { required: true, message: '请输入楼盘对接人', trigger: 'blur' },
    ],
    contactPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        {
            message: '请输入正确的电话号码',
            pattern: /^1[3-9]\d{9}$/,
            trigger: 'blur',
        },
    ],
    consultantName: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    consultantPhone: [
        { required: true, message: '请输入', trigger: 'blur' },
        {
            message: '请输入正确的电话号码',
            pattern: /^1[3-9]\d{9}$/,
            trigger: 'blur',
        },
    ],

})
const businessModulesList = ref([])
const projectList = ref([])
const plate = ref()
const list = ref([])
const state = ref(cloneDeep(initialState))
const searchConditions = ref(cloneDeep(initialState))

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

// 查询列表
const params = computed(() => ({
    buildingName: searchConditions.value?.buildingName, // 项目名称
    contactName: searchConditions.value?.contactName, // 券名称
    contactPhone: searchConditions.value?.contactPhone,
    consultant: searchConditions.value?.consultant,
    createTimeStart: searchConditions.value.createTime?.[0] ? formatTime(searchConditions.value?.createTime[0], 'yyyy-MM-dd 00:00:00') : '',
    createTimeEnd: searchConditions.value.createTime?.[1] ? formatTime(searchConditions.value?.createTime[1], 'yyyy-MM-dd 23:59:59') : '',
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
}))
const { data, isLoading, refetch } = useQueryContactPersonList(params)
watchEffect(() => {
    if (data.value) {
        if (data.value.rows && data.value.rows.length > 0) {
            list.value = cloneDeep(data.value.rows).reduce((pre: any, cur: any) => {
                cur.consultant1Name = JSON.parse(cur.consultantJson)?.[0]?.consultantName
                cur.consultant1Phone = JSON.parse(cur.consultantJson)?.[0]?.consultantPhone
                pre.push(cur)
                return pre
            }, [])
            tablePage.value.total = data.value.total
        }
    }
})

// 删除
const { mutate: delMuTate } = useDeleteBuildingContact()

function changeProject(val) {
    const item = projectList.value.filter((it) => {
        return val === it.id
    })
    form.buildingName = item[0].ghxmmc
}

const columns = ref([
    {
        label: '楼盘名称',
        prop: 'buildingName',
        valueType: 'copy',
    },
    {
        label: '楼盘对接人',
        prop: 'contactName',
        valueType: 'copy',
    },
    {
        label: '置业顾问',
        prop: 'consultant',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            endPlaceholder: '请选择结束时间',
            format: 'YYYY-MM-DD',
            startPlaceholder: '请选择开始时间',
            type: 'daterange',
        },
        label: '创建时间',
        prop: 'createTime',
        valueType: 'date-picker',
    },

])

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'buildingName', minWidth: 200, title: '楼盘名称' },
        { field: 'contactName', minWidth: 150, title: '楼盘对接人' },
        { field: 'contactPhone', minWidth: 100, title: '对接人电话' },
        { field: 'consultant1Name', minWidth: 100, title: '置业顾问' },
        { field: 'consultant1Phone', minWidth: 100, title: '置业顾问电话' },
        { field: 'createBy', minWidth: 100, title: '创建人' },
        { field: 'createTime', minWidth: 100, title: '创建时间' },
        { fixed: 'right', minWidth: 210, slots: { default: 'operate' }, title: '操作' },
    ],
})

// const dialogVisible = ref(false)
// const couponId = ref()

init()

/**
 * methods start
 */

const saveRow = throttle((formEl: any) => {
    if (form.id) {
        if (!validateConsultants(form.consultantList)) {
            ElMessage.warning('请完善表单')
            return
        }
        const pattern = /^1[3-9]\d{9}$/
        const isPhoneNoValid = form.consultantList.some(item => !pattern.test(item.consultantPhone))
        if (isPhoneNoValid) {
            ElMessage.warning('请填写正确的手机号')
            return
        }
        if (!formEl)
            return
        // 校验置业顾问手机号
        formEl.validate((valid) => {
            if (valid) {
                addBuildingContact({
                    id: form.id,
                    projectBaseId: form.projectBaseId,
                    buildingName: form.buildingName,
                    contactName: form.contactName,
                    contactPhone: form.contactPhone,
                    createBy: userStore.getUserInfo?.name,
                    consultant1Name: form.consultantList[0].consultantName,
                    consultant1Phone: form.consultantList[0].consultantPhone,
                    consultant2Name: form.consultantList.length > 1 ? form.consultantList[1].consultantName : undefined,
                    consultant2Phone: form.consultantList.length > 1 ? form.consultantList[1].consultantPhone : undefined,
                    consultantJson: JSON.stringify(form.consultantList),
                }).then((res) => {
                    if (res.code === 200) {
                        ElMessage.success('操作成功')
                        closeDialog()
                        refetch()
                    }
                    else {
                        ElMessage.warning(res.msg)
                    }
                })
            }
        })
    }
    else {
        if (!validateConsultants(form.consultantList)) {
            ElMessage.warning('请完善表单')
            return
        }
        const pattern = /^1[3-9]\d{9}$/
        const isPhoneNoValid = form.consultantList.some(item => !pattern.test(item.consultantPhone))
        if (isPhoneNoValid) {
            ElMessage.warning('请填写正确的手机号')
        }
        if (!formEl)
            return
        formEl.validate((valid) => {
            if (valid) {
                addBuildingContact({
                    projectBaseId: form.projectBaseId,
                    buildingName: form.buildingName,
                    contactName: form.contactName,
                    contactPhone: form.contactPhone,
                    createBy: userStore.getUserInfo?.name,
                    consultant1Name: form.consultantList[0].consultantName,
                    consultant1Phone: form.consultantList[0].consultantPhone,
                    consultant2Name: form.consultantList.length > 1 ? form.consultantList[1].consultantName : undefined,
                    consultant2Phone: form.consultantList.length > 1 ? form.consultantList[1].consultantPhone : undefined,
                    consultantJson: JSON.stringify(form.consultantList),
                }).then((res) => {
                    if (res.code === 200) {
                        ElMessage.success(res.msg)
                        closeDialog()
                        refetch()
                    }
                    else {
                        ElMessage.warning(res.msg)
                    }
                })
            }
        })
    }
}, 3000)

function validateConsultants(arr) {
    return arr.every((item) => {
        return item.consultantName && item.consultantPhone
    })
}

function closeDialog() {
    form.state = ''
    form.projectBaseId = ''
    form.buildingName = ''
    form.contactName = ''
    form.contactPhone = ''
    form.id = ''
    form.consultantList = [
        {
            consultantName: '',
            consultantPhone: '',
        },
    ]

    if (formRef.value) {
        formRef.value.resetFields()
    }
    addVisible.value = false
    form.id = ''
}

function editRow(row) {
    addVisible.value = true
    form.id = row.id
    form.state = row.state
    form.projectBaseId = row.projectBaseId
    form.buildingName = row.buildingName
    form.contactName = row.contactName
    form.contactPhone = row.contactPhone
    if (row.consultantJson) {
        form.consultantList = JSON.parse(row.consultantJson)
    }
    else {
        form.consultantList = [
            {
                consultantName: '',
                consultantPhone: '',
            },
        ]
    }

    getProjectList({
        pageNum: 1,
        pageSize: 10000,
    }).then((res) => {
        projectList.value = res.rows
    })
}

function init() {
    // getDataList()
    // getBusinessModules()
}

function addRow() {
    addVisible.value = true
    getProjectList({
        pageNum: 1,
        pageSize: 10000,
    }).then((res) => {
        projectList.value = res.rows
    })
}

// 获取折扣劵列表
// function getDataList() {
//     queryContactPersonList({
//         pageNum: tablePage.value.currentPage,
//         pageSize: tablePage.value.pageSize,
//     }).then((res) => {
//         if (res.code === 200) {
//             list.value = res.rows.reduce((pre: any, cur: any) => {
//                 cur.consultant1Name = JSON.parse(cur.consultantJson)?.[0]?.consultantName
//                 cur.consultant1Phone = JSON.parse(cur.consultantJson)?.[0]?.consultantPhone
//                 pre.push(cur)
//                 return pre
//             }, [])
//             tablePage.value.total = res.total
//         }
//     })
// }

const formRef = ref(null)
function resetSearch() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    plate.value = undefined
    // getDataList()
}

function submitSearch() {
    searchConditions.value = cloneDeep(state.value)
    tablePage.value.currentPage = 1
    // getDataList()
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    // getDataList()
}

// 跳转详情（新增、编辑）页面
function toPage(name, type, row) {
    const id = type === 'add' ? 'item' : row.id
    router.push({ name, params: { id, type } })
}

// 启用/禁用优惠券
function setStatus(row) {
    couponEnable({ id: row.id }).then(() => {
        ElMessage.success('操作成功')
        // getDataList()
    })
}

function addContractRow() {
    if (form.consultantList.length >= 4) {
        ElMessage.warning('至多添加4个置业顾问信息')
        return false
    }
    form.consultantList.push(
        {
            consultantName: '',
            consultantPhone: '',
        },
    )
}

function deleteContractRow(index) {
    if (form.consultantList.length <= 1) {
        ElMessage.warning('最少保留1个置业顾问信息')
        return false
    }
    form.consultantList.splice(index, 1)
}

function deleteRow(row) {
    ElMessageBox.confirm(
        `是否确认删除此记录`,
        '系统提示',
        {
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            type: 'warning',
        },
    ).then(() => {
        // deleteBuildingContact({ contactId: row.id }).then((res) => {
        //     // getDataList()
        // })
        delMuTate(row.id, {
            onSuccess: () => {
                ElMessage.success('操作成功')
            },
        })
    })
}

/**
 * methods end
 */
</script>

<template>
    <div class="activity-coupon-manage">
        <ElCard class="mb-20"
                shadow="never"
        >
            <SearchForm v-model="state"
                        :columns="columns"
                        submit-text="搜索"
                        @reset="resetSearch"
                        @submit="submitSearch"
            >
                <template #plus-field-plate>
                    <el-select v-model="plate">
                        <el-option v-for="item in businessModulesList"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.value"
                                   :disabled="item.disabled"
                        />
                    </el-select>
                </template>
            </SearchForm>
        </ElCard>

        <ElCard shadow="never">
            <SearchTable v-bind="gridOptions"
                         v-model:pager="tablePage"
                         :loading="isLoading"
                         :data="list"
                         @page-change="handlePageChange"
            >
                <template #toolbar_buttons>
                    <el-button plain
                               type="primary"
                               @click="addRow()"
                    >
                        新增
                    </el-button>
                </template>

                <template #time="{ row }">
                    {{ row.startTime }} ~ {{ row.endTime }}
                </template>

                <template #status="{ row }">
                    {{ ['已结束', '进行中'][row.enableStatus] }}
                </template>

                <template #enableStatus="{ row }">
                    <el-switch v-model="row.enableStatus"
                               :active-value="1"
                               :inactive-value="0"
                               @change="setStatus(row)"
                    />
                </template>

                <template #operate="{ row }">
                    <div class="operate-btns">
                        <el-button type="primary"
                                   text
                                   @click="editRow(row)"
                        >
                            编辑
                        </el-button>

                        <el-button type="primary"
                                   text
                                   @click="deleteRow(row)"
                        >
                            删除
                        </el-button>
                    </div>
                </template>
            </SearchTable>
        </ElCard>

        <el-dialog v-model="addVisible"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   :title="form.id ? '编辑楼盘联系人' : '新增楼盘联系人'"
                   width="900"
                   modal-class="contract-data-dialog"
                   draggable
                   destroy-on-close
                   @close="closeDialog"
        >
            <el-form ref="formRef"
                     :model="form"
                     :rules="formRules"
                     label-width="140"
            >
                <el-form-item label="所属楼盘"
                              prop="projectBaseId"
                >
                    <el-select v-model="form.projectBaseId"
                               placeholder="请选择所属楼盘"
                               clearable
                               filterable
                               @change="changeProject"
                    >
                        <el-option v-for="item in projectList"
                                   :key="item.value"
                                   :value="item.id"
                                   :label="item.xmmc"
                        />
                    </el-select>
                </el-form-item>

                <el-row>
                    <el-col :span="11">
                        <el-form-item label="楼盘对接人姓名"
                                      prop="contactName"
                        >
                            <el-input v-model="form.contactName"
                                      placeholder="请输入"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="11">
                        <el-form-item label="楼盘对接人电话"
                                      prop="contactPhone"
                        >
                            <el-input v-model="form.contactPhone"
                                      placeholder="请输入"
                                      maxlength="11"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row v-for="(item, index) in form.consultantList"
                        :key="index"
                >
                    <el-col :span="11">
                        <el-form-item label="置业顾问姓名"
                                      class="is-required"
                        >
                            <el-input v-model="item.consultantName"
                                      placeholder="请输入"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="11">
                        <el-form-item label="置业顾问电话"
                                      class="is-required"
                        >
                            <el-input v-model="item.consultantPhone"
                                      placeholder="请输入"
                                      maxlength="11"
                            />
                        </el-form-item>
                    </el-col>

                    <span v-if="index === 0"
                          style="margin-top: 6px;margin-left:10px;color:red;cursor: pointer;"
                          @click="addContractRow"
                    >添加</span>

                    <span v-if="index !== 0"
                          style="margin-top: 6px;margin-left:10px;color:red;cursor: pointer;"
                          @click="deleteContractRow(index)"
                    >删除</span>
                </el-row>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeDialog">取消</el-button>

                    <el-button type="primary"
                               @click="saveRow(formRef)"
                    >
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.coupon-data-dialog {
}
:deep(.coupon-data-dialog .el-dialog) {
    height: calc(100vh - 120px) !important;
}
:deep(.coupon-data-dialog .el-dialog__body) {
    overflow: hidden;
    overflow-y: auto;
}
:deep(.operate-btns .el-button) {
    margin: 0;
    padding: 6px;
}

:deep(.contract-data-dialog .el-dialog) {
    max-height: calc(100vh - 120px) !important;
}
</style>
